package com.atguigu.tingshu.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private OrderInfoFeignClient orderInfoFeignClient;

    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig;

    @Autowired
    private WxPayV3Config wxPayV3Config;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    //发起微信支付
    @Override
    public Map createJsapi(String paymentType, String orderNo, Long userId) {
        //1 判断：如果订单已经取消，不需要支付
        //	根据业务判断类型：
        //	充值业务不需要判断当前订单是否取消
        if (!paymentType.equals(SystemConstant.PAYMENT_TYPE_RECHARGE)){
            //	查询当前订单状态，如果订单状态已经取消，则不能生成二维码！
            Result<OrderInfo> orderInfoResult = this.orderInfoFeignClient.getOrderInfo(orderNo);
            OrderInfo orderInfo = orderInfoResult.getData();
            if (SystemConstant.ORDER_STATUS_CANCEL.equals(orderInfo.getOrderStatus())){
                //	此时订单已取消，不能生成二维码！
                return null;
            }
        }

        //2 添加支付记录：未支付状态   payment_info
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo);

        //3 调用微信支付接口发起支付
        //创建微信封装对象
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();

        //创建微信封装request对象，设置发起支付需要参数
        PrepayRequest request = new PrepayRequest();
        //com.wechat.pay.java.service.payments.jsapi.model.Amount
        //支付金额
        Amount amount = new Amount();
        amount.setTotal(1);  //TODO 支付0.01
        request.setAmount(amount);

        request.setAppid(wxPayV3Config.getAppid());
        request.setMchid(wxPayV3Config.getMerchantId());
        request.setDescription(paymentInfo.getContent());
        //回调地址
        request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
        //订单编号
        request.setOutTradeNo(paymentInfo.getOrderNo());

        //	获取用户信息
        Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(paymentInfo.getUserId());
        Assert.notNull(userInfoVoResult,"返回用户结果集对象不能为空");
        UserInfoVo userInfoVo = userInfoVoResult.getData();
        Assert.notNull(userInfoVo,"用户对象不能为空");
        String openid = userInfoVo.getWxOpenId();
        //openid
        Payer payer = new Payer();
        payer.setOpenid(openid);
        request.setPayer(payer);

        //调用方法发起微信支付
        PrepayWithRequestPaymentResponse response =
                service.prepayWithRequestPayment(request);

        Map<String, Object> result = new HashMap();
        result.put("timeStamp", response.getTimeStamp());
        result.put("nonceStr", response.getNonceStr());
        result.put("package", response.getPackageVal());
        result.put("signType", response.getSignType());
        result.put("paySign", response.getPaySign());
        //	返回数据
        return result;
    }

    @Override
    public Transaction queryPayStatus(String orderNo) {
        try {
            //	构建service
            JsapiServiceExtension service =
                    new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();

            QueryOrderByOutTradeNoRequest queryRequest = new QueryOrderByOutTradeNoRequest();

            queryRequest.setMchid(wxPayV3Config.getMerchantId());
            queryRequest.setOutTradeNo(orderNo);

            Transaction result = service.queryOrderByOutTradeNo(queryRequest);
            log.info("Transaction:\t"+JSON.toJSONString(result));
            return result ;
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void wxnotify(HttpServletRequest request) {
        //1.回调通知的验签与解密
        //从request头信息获取参数
        //HTTP 头 Wechatpay-Signature
        // HTTP 头 Wechatpay-Nonce
        //HTTP 头 Wechatpay-Timestamp
        //HTTP 头 Wechatpay-Serial
        //HTTP 头 Wechatpay-Signature-Type
        //HTTP 请求体 body。切记使用原始报文，不要用 JSON 对象序列化后的字符串，避免验签的 body 和原文不一致。
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String signature = request.getHeader("Wechatpay-Signature");
        // 调用工具类来获取请求体数据
        String requestBody = PayUtil.readData(request);

        //2.构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .body(requestBody)
                .build();

        //3.初始化 NotificationParser
        NotificationParser parser = new NotificationParser(rsaAutoCertificateConfig);
        //4.以支付通知回调为例，验签、解密并转换成 Transaction
        Transaction transaction = parser.parse(requestParam, Transaction.class);
        log.info("成功解析：{}", JSON.toJSONString(transaction));
        if(null != transaction && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
            // 5.处理支付业务
            paymentInfoService.updatePaymentStatus(transaction);
        }
    }

    @Override
    public Map<String, Object> createNative(String paymentType, String orderNo, Long userId) {
        try {
            //保存支付记录
            PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo);

            // 构建service
            NativePayService service = new NativePayService.Builder().config(rsaAutoCertificateConfig).build();
            // request.setXxx(val)设置所需参数，具体参数可见Request定义
            com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest request = new com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest();
            com.wechat.pay.java.service.payments.nativepay.model.Amount amount = new com.wechat.pay.java.service.payments.nativepay.model.Amount();
            amount.setTotal(1);
            request.setAmount(amount);
            request.setAppid(wxPayV3Config.getAppid());
            request.setMchid(wxPayV3Config.getMerchantId());
            request.setDescription(paymentInfo.getContent());
            request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
            request.setOutTradeNo(paymentInfo.getOrderNo());

            // 调用下单方法，得到应答
            com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse response = service.prepay(request);
            // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
            System.out.println(response.getCodeUrl());

            Map result = new HashMap<>();
            result.put("codeUrl", response.getCodeUrl());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException( 201, "微信下单异常");
        }
    }
}
